<template>
    <!-- 面板头部 -->
    <panelHead :route="route" />

    <!-- 账号管理表格 element-plus -->
    <el-table :data="tableData.list" style="width: 100%">
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="permissions_id" label="所属组别">
            <template #default="scope">
                {{ getAuthName(scope.row.permissions_id) }}
            </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="active" label="状态">
            <template #default="scope">
                <el-tag :type="scope.row.active ? 'success' : 'danger'">{{ scope.row.active ? '正常' : '异常' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
            <template #default="scope">
                <div class="flex-box">
                    <el-icon>
                        <Clock />
                    </el-icon>
                    <span style="margin-left: 10px;">{{ scope.row.create_time }}</span>
                </div>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <!-- scope.row 表示当前行的数据对象 -->
                <el-button type="primary" @click="open(scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination :getList="getAuthAdminList" />

    <!-- 添加账号弹窗 -->
    <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="编辑用户" width="500">
        <!-- label-position="left" 标签位置 -->
        <el-form :model="form" ref="formRef" :rules="rules" label-width="auto" label-position="left">

            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="form.mobile" disabled />
            </el-form-item>
            <el-form-item label="昵称" prop="name">
                <el-input v-model="form.name" placeholder="请填写昵称" />
            </el-form-item>

            <el-form-item label="菜单权限" prop="permissions_id">
                <el-select v-model="form.permissions_id" placeholder="请选择菜单权限" style="width: 240px">
                    <el-option v-for="item in authList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>

        </el-form>
        <!-- 确认按钮 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="confirm(formRef)">确认</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script setup name="Admin">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { authAdmin, menuSelectList, updateUser } from '../../../api'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'
import Pagination from '@/components/pagination.vue'
const route = useRoute()

// 弹窗表单组件实例
const formRef = ref(null)

// 弹窗表单数据
const form = reactive({
    name: '',
    mobile: '',
    permissions_id: '',
})

// 弹窗是否显示
const dialogFormVisible = ref(false)

// 关闭弹窗的回调
const beforeClose = () => {
    dialogFormVisible.value = false
}

// 打开弹窗
const open = (rowData) => {
    dialogFormVisible.value = true
    // 弹窗打开时form生成是异步的
    nextTick(() => {
        // 将rowData中的数据赋值给form
        Object.assign(form, { name: rowData.name, mobile: rowData.mobile, permissions_id: rowData.permissions_id })
    })
}

// 弹窗表单验证  trigger: 'blur' 失去焦点时触发
const rules = reactive({
    // required: true 必填 message: 提示信息
    name: [{ required: true, trigger: 'blur', message: '请输入昵称' }],
    permissions_id: [{ required: true, trigger: 'blur', message: '请选择菜单权限' }]
})
// 确认按钮 弹窗表单提交校验 element-plus
const confirm = async (formEl) => {
    if (!formEl) return
    // 手动触发弹窗表单验证
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 调用账号修改网络请求 将弹窗表单数据传递给后端
            updateUser({
                name: form.name,
                permissions_id: form.permissions_id
            }).then(({ data }) => {
                if (data.code === 10000) {
                    ElMessage.success('账号修改成功')
                    // 关闭弹窗重置表单
                    beforeClose()
                    // 刷新账号管理列表
                    getAuthAdminList()
                } else {
                    ElMessage.error('账号修改失败', data.msg)
                }
            })
        } else {
            console.log('error submit!!', fields)
        }
    }
    )
}

// 权限下拉列表数据
const authList = ref([])

// 根据权限id匹配权限名称
const getAuthName = (id) => {
    // ?.name (可选链) 如果找不到，则返回 '超级管理员'
    return authList.value.find(item => item.id === id)?.name || '超级管理员'
}

// 账号管理列表数据
const tableData = reactive({
    list: [],
    total: 0
})


onMounted(() => {
    // 获取账号管理列表
    getAuthAdminList()
    // 获取权限下拉列表
    menuSelectList().then(({ data }) => {
        console.log(data)
        authList.value = data.data
    })
})

// 分页数据
const paginationData = reactive({
    pageNum: 1, // 当前页码
    pageSize: 10 // 每页条数
})

// 分页条数改变
const handleSizeChange = (size) => {
    paginationData.pageSize = size
    getAuthAdminList()
}

// 分页页码改变
const handleCurrentChange = (pageNum) => {
    paginationData.pageNum = pageNum
    getAuthAdminList()
}

// 获取账号管理列表
const getAuthAdminList = () => {
    authAdmin(paginationData).then(({ data }) => {
        console.log(data)
        // 将获取到的数据赋值给tableData
        const { list, total } = data.data
        // 将时间戳转换为日期格式
        list.forEach(item => {
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD')
        })
        tableData.list = list
        tableData.total = total
    })
}
</script>

<style lang="less" scoped>
.flex-box {
    display: flex;
    align-items: center;
}
</style>